local Color = require 'game.color'

local UI = {}

function UI.listTiles(tiles, display, x, y)
    local mx, ox, oy = x, x, y
    local m = {}
    local n = {}
    for i = 1, #tiles do
        local tile = tiles[i]
        local t = m[tile.name]
        if not t then
            t = {}
            m[tile.name] = t
            n[#n + 1] = tile.name
        end
        t[#t + 1] = tiles[i]
    end
    table.sort(n)
    for i = 1, #n do
        local count = #m[n[i]]
        local tile = m[n[i]][1]
        x = ox

        display:write(tile.glyph, x, y, tile.color)

        x = x + 2

        if tile.health then
            for j = 1, count do
                tile = m[n[i]][j]
                local r = (tile.health / tile.maxHealth)
                local c2 = math.min(math.floor(r * 240), 120)
                local c1 = math.min(math.floor((1 - r) * 240), 120)
                display:write(' ', x, y, nil, { 80 + c1, 80 + c2, 80 })
                x = x + 1
            end
            x = x + 1
        end

        local s = count > 1 and (tile.name .. ' x' .. tostring(count)) or tile.name
        display:write(s, x, y, Color.bright)
        mx = math.max(mx, x + s:len() + 1)
        y = y + 1
    end
    return mx, y
end

return UI
